package com.lpit.service.impl;

import com.lpit.constant.EsIndexConstant;
import com.lpit.dto.ArticleSearchDto;
import com.lpit.pojo.Article;
import com.lpit.result.ResponseResult;
import com.lpit.service.ArticleSearchService;
import io.searchbox.client.JestClient;
import io.searchbox.core.Search;
import io.searchbox.core.SearchResult;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.Date;
import java.util.List;

@Service
public class ArticleSearchServiceImpl implements ArticleSearchService {

    @Autowired
    private JestClient jestClient;

    /**
     * 搜索文章
     * @param articleSearchDto
     * @return
     * @throws IOException
     */
    @Override
    public ResponseResult<List<?>> searchArticle(ArticleSearchDto articleSearchDto) throws IOException {
        if(null==articleSearchDto){
            articleSearchDto = new ArticleSearchDto();
        }
        if(null==articleSearchDto.getNewestTime()){
            articleSearchDto.setNewestTime(new Date().toString());
        }
        if(null==articleSearchDto.getSize()){
            articleSearchDto.setSize(10);
        }
        if(null==articleSearchDto.getFrom()){
            articleSearchDto.setFrom(1);
        }

        /* 创建一个SearchSourceBuilder对象，用于构建Elasticsearch的查询条件*/
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
        /*设置查询条件，这里使用termQuery方法创建一个关键词匹配查询，查找标题中包含关键词 “Builder对象” 的文章*/
        searchSourceBuilder.query(QueryBuilders.termQuery("article", articleSearchDto.getKeyword()));
        /*设置查询结果的起始位置*/
        searchSourceBuilder.from(articleSearchDto.getFrom());
        /*设置返回结果的最大数量*/
        searchSourceBuilder.size(articleSearchDto.getSize());

        /*创建一个Search对象，使用SearchSourceBuilder生成的查询条件，并指定索引名称和类型*/
        Search search = new Search.Builder(searchSourceBuilder.toString()).addIndex(EsIndexConstant.ALL_INDEX).addType("article").build();
        /*使用JestClient执行查询操作，将Search对象传递给execute()方法，返回查询结果*/
        SearchResult searchResult = jestClient.execute(search);
        /* 将查询结果转换为Article对象列表，通过getSourceAsObjectList()方法可以直接将文档源转换为指定的Java对象*/
        List<Article> sourceAsObjectList = searchResult.getSourceAsObjectList(Article.class);

        /*返回结果*/
        return new ResponseResult<>(sourceAsObjectList);
    }
}
